var tree = new Ext.tree.TreePanel({
    id: "tree-panel",
    title: "Repositories",
    region:"north",
    split: true,
    minSize: 150,
    autoScroll: true,
    // tree-specific configs:
    rootVisible: false,
    lines: false,
    singleExpand: true,
    useArrows: true,
    loader: new Ext.tree.TreeLoader(),
    root: new Ext.tree.AsyncTreeNode()
});

var syspstore = null;
var perpstore = null;
var sptlgtSystemArray = [];
var sptlgtPersonalArray = [];

function load_tree(response) {
    jsonResp = Ext.util.JSON.decode(response.responseText);
    var jsonRepositories = transformJsonRepos(jsonResp);
    var Tree = Ext.tree;

    tree.addListener("click", eventManager.fireNodeSelectEvent, eventManager);

    tree.addListener('expandnode', function(node) {
        if (node.id != "addamatreetopid") {
            Ext.Ajax.request({
                url: node.id + "/dir",
                method: "GET",
                success: function(response, opts) {
                    tree.suspendEvents();
                    load_children(node, response);
                    tree.resumeEvents();
                },
                failure: function(response, opts) {
                    node.expandable = false;
                }
            });
        }
    }, {single: true}); //end of expandnode listener

    tree.addListener("collapsenode", function(tnode) {
        tree.suspendEvents();
        tnode.suspendEvents();
        tnode.collapse(true);
        tnode.resumeEvents();
        tree.resumeEvents();
    }, {single: true}); //end of collapsenode and all other listeners

    // TODO: this seems unneeded
    /*var savedinitComponent = Ext.tree.TreePanel.prototype.initComponent;
     Ext.override(Ext.tree.TreePanel, {
     initComponent: function() {
     this.loader = new Ext.tree.TreeLoader();
     if (this.root && !this.root.render) {
     this.root = new Ext.tree.AsyncTreeNode(Ext.apply({}, this.root));
     }
     savedinitComponent.apply(this, arguments);
     }
     });
     */
    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: 'Repositories',
        draggable:false,
        id:'addamatreetopid',
        children: jsonRepositories
    });
    tree.setRootNode(root);
    tree.render();
    root.expand();
}

function loadRepositories() {

    var aurl = "/addama-rest";
    Ext.Ajax.request({
        url: aurl,
        method: "GET",
        success: function(response) {
            load_tree(response);

        },
        failure: function() {
            eventManager.fireStatusMessageEvent({
                text: "Failed to load repositories",
                level: "error"
            });
        }
    });


    //containerPanel.add(firstGrid);

}

function expandNode(node) {
    var uri = node.attributes.uri + "/dir";
    if (node.id != "addamatreetopid") {
        Ext.Ajax.request({
            url: uri,
            method: "GET",
            success: function(response) {
                node.suspendEvents();
                load_children(node, response);
            },
            failure: function(response) {
                eventManager.fireStatusMessageEvent({
                    text: "Failed to load node: " + node.id,
                    level: "error"
                });
            }
        });
    }
}

function load_children(node, response) {

    var jsonDecoded = Ext.util.JSON.decode(response.responseText);
    var jsonArr = null;
    var jsonArrDirs = transformJsonDirectories(jsonDecoded);
    var jsonArrFiles = transformJsonFiles(jsonDecoded);
    var dirArrayLength = 0;
    var fileArrayLength = 0;

    if (jsonArrDirs != null) {
        dirArrayLength = jsonArrDirs.length;
    }
    if (jsonArrFiles != null) {
        fileArrayLength = jsonArrFiles.length;
    }
    //add directories first
    if (jsonArrDirs != null || jsonArrFiles != null) {
        jsonArr = new Array(dirArrayLength + fileArrayLength);
    }
    if (jsonArrDirs != null) {
        for (var i = 0; i < jsonArrDirs.length; i++) {
            jsonArr[i] = jsonArrDirs[i];
        }
    }
    if (jsonArrFiles != null) {
        for (var i = 0; i < jsonArrFiles.length; i++) {
            jsonArr[dirArrayLength + i] = jsonArrFiles[i];
        }
    }

    if (jsonArr != null) {
        while (node.firstChild) {
            var c = node.firstChild;
            node.removeChild(c);
            c.destroy();
        }
        for (var i = 0; i < jsonArr.length; i++) {
            node.appendChild(jsonArr[i]);
        }
        node.renderChildren();
        node.suspendEvents();
        node.expand(false, false, function(node) {
            node.eachChild(function(child) {
                child.suspendEvents();
                child.resumeEvents();
            });
        });
        node.resumeEvents();
    }
}

/*
 Transformed json from response to extjs tree json structure
 */
function transformJsonDirectories(data) {
    //console.log("transforming json from ajax:" + data.repositories);
    //var repo = false;
    var jsonFolderObj = [];
    if (data.directories) {
        jsonFolderObj = data.directories;
    } else {
        //this deals with case where there are no directories, an empty folder basically
        var leafFolderObj = [];
        leafFolderObj.text = data.name;
        leafFolderObj.id = data.uri;
        leafFolderObj.path = data.uri;
        leafFolderObj.cls = "folder";
        leafFolderObj.leaf = false;
        leafFolderObj.children = [];
        jsonFolderObj[0] = leafFolderObj;
        return jsonFolderObj;
    }
    var folderArrayUri = [];
    var folderMap = [];

    if (jsonFolderObj != null) {
        for (var i = 0; i < jsonFolderObj.length; i++) {
            jsonFolderObj[i].text = jsonFolderObj[i].name;
            jsonFolderObj[i].id = jsonFolderObj[i].uri;
            jsonFolderObj[i].path = jsonFolderObj[i].uri;
            jsonFolderObj[i].cls = "folder";
            jsonFolderObj[i].leaf = false;
            jsonFolderObj[i].children = [];
            folderArrayUri[i] = jsonFolderObj[i].id;
            folderMap[jsonFolderObj[i].id] = jsonFolderObj[i];
        }
    }
    folderArrayUri.sort();
    var sortedJsonFolderObj = [];
    for (var si = 0; si < folderArrayUri.length; si++) {
        sortedJsonFolderObj[sortedJsonFolderObj.length] = folderMap[folderArrayUri[si]];
    }

    return sortedJsonFolderObj;
}

/*
 Transformed json from response to extjs tree json structure
 */
function transformJsonFiles(data) {
    //console.log("transforming json from ajax:" + data.repositories);
    //var repo = false;
    var jsonFilesObj = null;
    if (data.files) {
        jsonFilesObj = data.files;
    }
    var fileArrayUri = [];
    var fileMap = [];
    if (jsonFilesObj != null) {
        for (var i = 0; i < jsonFilesObj.length; i++) {
            jsonFilesObj[i].text = jsonFilesObj[i].name;
            jsonFilesObj[i].id = jsonFilesObj[i].uri;
            jsonFilesObj[i].path = jsonFilesObj[i].uri;
            jsonFilesObj[i].cls = "file";
            jsonFilesObj[i].leaf = true;
            fileArrayUri[i] = jsonFilesObj[i].id;
            fileMap[jsonFilesObj[i].id] = jsonFilesObj[i];
        }
    }

    fileArrayUri.sort();
    var sortedJsonFilesObj = [];
    for (var si = 0; si < fileArrayUri.length; si++) {
        sortedJsonFilesObj[sortedJsonFilesObj.length] = fileMap[fileArrayUri[si]];
    }

    return sortedJsonFilesObj;

}

/*
 Transformed json from response to extjs tree json structure
 */
function transformJsonRepos(data) {
    var jsonTransformed = data.repositories;
    if (jsonTransformed != null) {
        for (var i = 0; i < jsonTransformed.length; i++) {
            jsonTransformed[i].text = jsonTransformed[i].name;
            jsonTransformed[i].id = jsonTransformed[i].uri;
            jsonTransformed[i].path = jsonTransformed[i].uri;
            jsonTransformed[i].isRepository = true;
            jsonTransformed[i].cls = "repository";
            jsonTransformed[i].leaf = false;
            jsonTransformed[i].children = [];
        }
    }
    return jsonTransformed;
}

var spottabs = new Ext.TabPanel({
    width:450,
    activeTab: 0,
    frame:true,
    defaults:{autoHeight: true}
});


/*var containerPanel = {
    id: "panel-labels-browse-control",
    title: "Spotlights",
    region: "center",
    bodyStyle: "padding-bottom:15px; background:#eee;",
    autoScroll: true,
    contentEl: "panel-container",
    items: [spottabs]
};
*/
var spotlightPanel = new Ext.Panel({
    id: "panel-labels-browse-control",
    title: "Spotlights",
    bodyStyle: "padding-bottom:15px; background:#eee;",
    autoScroll: true,
    collapsible: true,
    contentEl: "panel-container",
    items: [spottabs]
});

var browsePanel = {
    layout: "accordion",
    id: "layout-browser",
    title: "Browse",
    region:"west",
    border: true,
    split: true,
    margins: "2 0 5 5",
    width: 275,
    minSize: 100,
    maxSize: 500,
    collapsible: true,
    layoutConfig: {
        titleCollapse: true,
        hideCollapseTool: true,
        animate: true,
        activeOnTop: false
    },
    items: [spotlightPanel,tree]
};

function sortAB(a,b){
        return a.name < b.name;
}

function loadRepositoriesAndSpotlights() {
    sptlght.utils.SpotlightUtils.getSystemSpotlightData(function() {
        syspstore = new Ext.data.ArrayStore({
            fields: sptlght.utils.SpotlightUtils.arrayFields,
            data: sptlgtSystemArray
        });
        spottabs.add(sptlght.utils.SpotlightUtils.getSpotlightGrid("System", syspstore));
    });
    sptlght.utils.SpotlightUtils.getPersonalSpotlightData(emailaddress, function() {
        perpstore = new Ext.data.ArrayStore({
            fields: sptlght.utils.SpotlightUtils.arrayFields,
            data: sptlgtPersonalArray
        });
        spottabs.add(sptlght.utils.SpotlightUtils.getSpotlightGrid("Personal",perpstore));
        loadRepositories();        
    });
} 

Ext.onReady(loadRepositoriesAndSpotlights);